import { uuid } from '@/utils'

import type { IndicatorMethod } from '@/types/modules/statistical-indicator'
import type { TableColumn } from '@/types/modules/public'

import { getFunctionList } from '@/api/modules/function'

export function useIndicatorMethods() {
  const [loading, setLoading] = useState(false)
  const columns: TableColumn<IndicatorMethod>[] = [
    { key: uuid(), label: '函数', prop: 'method' },
    { key: uuid(), label: '函数名称', prop: 'description' },
    { key: uuid(), label: '参数解释', prop: 'parameter' },
    { key: uuid(), label: '示例', prop: 'example' },
  ]
  const [lists, setLists] = useShallowState<
    IndicatorMethod[]
  >([])

  /**
   *
   * @param keyword
   * @param type 1-计算公式，2-统计公式
   */
  async function queryIndicatorMethods(keyword: string, type: 1 | 2) {
    setLoading(true)
    try {
      setLists([])
      const { data } = await getFunctionList(type, keyword)
      let i = 1
      setLists((data || []).map((v: any) => ({
        id: i++,
        method: v.functionFormula,
        description: v.functionName,
        parameter: v.parameterExplain,
        example: v.exampleExplain,
      })))
    }
    catch (e) {
    }
    finally {
      setLoading(false)
    }
  }

  return {
    loading,
    /** 函数列表 */
    lists,
    columns,
    setLists,
    setLoading,

    /** 模糊查询所有函数列表 */
    queryIndicatorMethods,
  }
}
